package com.ctsi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctsi.common.util.Search;
import com.ctsi.core.common.exception.ServiceException;
import com.ctsi.core.common.util.$;
import com.ctsi.system.entity.RoleMenu;
import com.ctsi.system.mapper.RoleMenuMapper;
import com.ctsi.system.service.IRoleMenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统角色菜单表 服务实现类
 * </p>
 *
 * @author wang xiao xiang
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements IRoleMenuService {

	@Override
	public IPage<RoleMenu> listPage(Page page, Search search) {
		LambdaQueryWrapper<RoleMenu> queryWrapper = new LambdaQueryWrapper<>();
		return this.baseMapper.selectPage(page, queryWrapper);
	}

	@Override
	public List<Long> getRoleMenuIdList(List<Long> roleIdList) {
		return this.list(Wrappers.<RoleMenu>query().lambda()
				.in(RoleMenu::getRoleId, roleIdList))
				.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());

	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean grantMenu(Long id, List<Long> ids) {
		if ($.isEmpty(id) || $.isEmpty(ids)) {
			throw new ServiceException("您输入的部分数据为空！");
		}
		//　先删除已有的角色菜单
		this.remove(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getRoleId, id));

		// 授权菜单
		ids.forEach(menuId -> {
			RoleMenu roleMenu = new RoleMenu();
			roleMenu.setMenuId(menuId);
			roleMenu.setRoleId(id);
			this.save(roleMenu);
		});

		return Boolean.TRUE;
	}
}
